package com.ebo.synframework.nettybase.protoPool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;


/**
 * 指定proto类型的Builder池
 *
 */
public class ProtoBuilderPool implements BlockingProtoBuilderPool{
	
	private static final int init_size = 15;
	
	private String protoName;
	
	private BlockingQueue<ReusedProtoBuilder> pool;
	
	private static final Logger logger = Logger.getLogger(ProtoBuilderPool.class);
	
	public ProtoBuilderPool(Class<?> proto){
		protoName = proto.getSimpleName();
		pool = new LinkedBlockingQueue<ReusedProtoBuilder>();
		initPool(protoName);
	}
	
	/**
	 * 初始化池
	 * @param protoName
	 */
	private void initPool(String protoName){
		for(int i=0; i<init_size; i++){
			pool.offer(new ReusedProtoBuilder(protoName, this));
		}
	}
	
	@Override
	public ReusedProtoBuilder get(){
		ReusedProtoBuilder builder = null;
		try{
			builder= pool.poll();
			if(builder==null){
				logger.info("poll builder "+protoName+" return null, new another one add to the pool and return");
				ReusedProtoBuilder builder0 = new ReusedProtoBuilder(protoName, this);
				return builder0;
			}
			return builder;
		}catch (Exception e) {
			logger.error("get proto meet an error "+e);
			if(builder==null){
				ReusedProtoBuilder builder0 = new ReusedProtoBuilder(protoName, this);
				return builder0;
			}
		}
		return builder;
	}
	
	@Override
	public void release(ReusedProtoBuilder builder){
		pool.offer(builder);
	}
	
	public String getProtoName(){
		return protoName;
	}
	
	public int getPoolSize(){
		return pool.size();
	}
}
